package demo.sip;

import cn.qiao.netty.demo.SipDecoder;
import cn.qiao.netty.demo.SipEncoder;
import cn.qiao.netty.demo.demo.sip.DefaultSipRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.pkts.buffer.Buffers;
import io.pkts.packet.sip.SipMessage;
import io.pkts.packet.sip.impl.SipParser;

public class NettySipClient {

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) {
                     ch.pipeline().addLast(new SipEncoder());
                     ch.pipeline().addLast(new SipDecoder());
                     ch.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
                         @Override
                         protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                             System.out.println(msg);
                         }
                     });
                 }
             });

            // Start the client.
            ChannelFuture f = b.connect("192.168.1.3", 5060).sync();
            String s = "REGISTER sip:192.168.1.3:5062;transport=TCP SIP/2.0\n" +
                    "Via: SIP/2.0/TCP 192.168.1.3:62855;branch=z9hG4bK-524287-1---e6a2fb64efd34dac;rport\n" +
                    "Max-Forwards: 70\n" +
                    "Contact: <sip:1001@192.168.1.3:62855;rinstance=519190261b57067a;transport=tcp>\n" +
                    "To: <sip:1001@192.168.1.3:5062;transport=TCP>\n" +
                    "From: <sip:1001@192.168.1.3:5062;transport=TCP>;tag=bb7fed5e\n" +
                    "Call-ID: w1ltUqw_H031G6jRFDckDw..\n" +
                    "CSeq: 1 REGISTER\n" +
                    "Expires: 70\n" +
                    "Allow: INVITE, ACK, CANCEL, BYE, NOTIFY, REFER, MESSAGE, OPTIONS, INFO, SUBSCRIBE\n" +
                    "Supported: replaces, norefersub, extended-refer, timer, sec-agree, outbound, path, X-cisco-serviceuri\n" +
                    "User-Agent: Z 5.6.2 v2.10.20.2\n" +
                    "Allow-Events: presence, kpml, talk, as-feature-event\n" +
                    "Content-Length: 0\n" +
                    "\n";
            SipMessage frame = SipParser.frame(Buffers.wrap(s));
            f.channel().writeAndFlush(frame);
            // Wait for the server to close the connection.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down the event loop to terminate all threads.
            group.shutdownGracefully();
        }
    }
}